//
//  CGPurchaseViewController.m
//  SchoolClient
//
//  Created by mac on 15/11/3.
//  Copyright © 2015年 mac. All rights reserved.
/*
 支付宝 的端口
 帐号  lemon_ltd@163.com
 登录密码   a123456789?.
 支付密码   a123456789
 
 */

#import "CGPurchaseViewController.h"

#import "Order.h"
#import "DataSigner.h"
#import <AlipaySDK/AlipaySDK.h>
#import "CGAlipayResult.h"

@interface CGPurchaseViewController ()

@property(nonatomic,strong)UILabel *priceLabel;
@property(nonatomic,strong)NSString *partner;
@property(nonatomic,strong)NSString *seller;
@property(nonatomic,strong)NSString *privateKey;
@property(nonatomic,strong)NSDictionary *alipayResponse;

@end

@implementation CGPurchaseViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [Tools getColor:@"ebebeb"];
    self.title = @"认证会员";
    
    
   //实名认证时的商户ID
    self.partner = @"2088911971998419";
   //商户的支付宝账号
    self.seller = @"lemon_ltd@163.com";
   //商户私钥 pkcs8格式
    self.privateKey = @"MIICXgIBAAKBgQDLyzLs+hYIl4vokoEA5AeX1hLJ7Q809E/I1dX//+kRJa76cJJb7CiOkyH3MqgPAfRoJUb1l5M5RPC/sEyJuq8o2dJlAl38JMlXDLYixEHFgU0KMm0ljKmp5JILcqdVOvIlIYJuGTjhydhyDGll5isKSHwwG1Kah3T9ATLPfuhQjQIDAQABAoGBAKE8XEdHueUEWaohNzWINEW6FlVyXESuQu2H2W9YfoKViPIV3IYjuxbKa+YTSwnMpx062QB38wAtfjh6+KNDc055mHI2ZoNvotrb6/pMo/6WnHM+uGr5uRwdcAq1F1IEtwkiXHNz7ZxlR7mBWFXohZN/Do4uIYMmZugfEjZn2gvVAkEA81gEXJupTeca3EfplVO/0OSK4bc94G12PxiyfGuoRCgosvV01ERg+S3TleLYuWSlhChALUwoBP8lVdaac24k9wJBANZkmG8XLjMTOEUnJBz2NkIt9lnUzv2sm7rwtsxOWkUxHZQSGNTGryRAymisKrt33fKsYGV30H/9zlueD/7eyZsCQQDp/ZakHiIcgL85VgTrzA5EJZ7OEE91gIwVfAAU18iDUUJhYtkmS2Ib+M7d77WJ/5eQjsu3QuWweE9ETQlTOXRdAkBl2/t0ZF4F1C7a5CLLQ8s5nB68RVhmu7htk+o1nVBUKWa1L/fuN8uEfOft3UacNPIVVwKhktBTzyFY8/sDi5PbAkEAvupHV4V0wKTt7N4Cecs0zdDniWQG9Q/pKPKSp414JSzY84WW346mBfe2zAkQ13VoxkOsbi6dmpGFZWARAKQcSw==";
    
    //发送请求获取VIP价格
    [self fetchVipPriceWithRequest];
    
    [self initTableView];
    [self layoutUI];
    

    
}

-(void)initTableView{
    
    CGRect aRect = CGRectMake(0,0,SCREEN_WIDTH,SCREEN_HEIGHT);
    self.tableView = [[UITableView alloc] initWithFrame:aRect  style:UITableViewStyleGrouped];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
    self.tableView.autoresizingMask = UIViewAutoresizingFlexibleWidth;
    self.tableView.backgroundColor = [UIColor clearColor];
    [self.view addSubview: self.tableView];
}

-(void)layoutUI{
    UIView *containView = [[UIView alloc]initWithFrame:CGRectMake(0, 135, SCREEN_WIDTH, 210)];
    containView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:containView];
    //一、认证会员介绍:
    CGRect aFrame = CGRectMake(10, 0, SCREEN_WIDTH - 20, 30);
    UILabel *firstTitleLabel = [[UILabel alloc]initWithFrame:aFrame];
    firstTitleLabel.text = @"1.你将享有校园招聘信息。";
    [containView addSubview:firstTitleLabel];
    firstTitleLabel.font = [UIFont systemFontOfSize:14];
    //内容
    aFrame.origin.y += 30;
    UILabel *contentLabel1 = [[UILabel alloc] initWithFrame:aFrame];
    //contentLabel1.backgroundColor = [UIColor yellowColor];
    contentLabel1.text = @"2.你将享有社会招聘信息。";
    contentLabel1.font = [UIFont systemFontOfSize:14];
    contentLabel1.numberOfLines = 0;
    //高度随字体的行数改变
    CGRect contentBounds = CGRectMake(0, 0, contentLabel1.frame.size.width, 999);
    contentLabel1.bounds = [contentLabel1 textRectForBounds:contentBounds limitedToNumberOfLines:0];
    [containView addSubview:contentLabel1];
    contentLabel1.frame = CGRectMake(10, 30, SCREEN_WIDTH - 20, contentLabel1.bounds.size.height);
   
//    //二、如何成为VIP:
    aFrame = contentLabel1.frame;
//    aFrame.origin.y = 65;
//    UILabel *secondTitleLabel = [[UILabel alloc]initWithFrame:aFrame];
//    secondTitleLabel.text = @"3.将享有档案相关服务。";
//    [containView addSubview:secondTitleLabel];
//    secondTitleLabel.font = [UIFont systemFontOfSize:14];
    //内容
//    aFrame.origin.y += 30;
//    aFrame.size.height = 25;
//    UILabel *label = [[UILabel alloc]initWithFrame:aFrame];
//    label.text = @"(1)、档案查询：每年3月、9月固定更新截至本年内3月1日、9月1日前档案位置信息。";
//    label.font = [UIFont systemFontOfSize:14];
//    [containView addSubview:label];
//
    
    aFrame.origin.y += 25;
    UILabel *contentLabel2 = [[UILabel alloc] initWithFrame:aFrame];
    //contentLabel2.backgroundColor = [UIColor yellowColor];
    contentLabel2.text = @"3.将享有档案相关服务。\n(1)、档案查询:每年3月、9月固定更新截至本年内3月1日、9月1日前档案位置信息。\n(2)、档案代办:提交申请并通过客服沟通提交所需材料后，以所在自然月为限，月底统一办理代办服务。";
    contentLabel2.font = [UIFont systemFontOfSize:14];
    contentLabel2.numberOfLines = 0;
    //高度随字体的行数改变
    contentBounds = CGRectMake(0, 0, contentLabel2.frame.size.width, 999);
    contentLabel2.bounds = [contentLabel2 textRectForBounds:contentBounds limitedToNumberOfLines:0];
    [containView addSubview:contentLabel2];
    contentLabel2.frame = CGRectMake(10, aFrame.origin.y, SCREEN_WIDTH - 20, contentLabel2.bounds.size.height);
    
    aFrame = contentLabel2.frame;
    aFrame.origin.y += 100;
    aFrame.size.height = 40;
    UILabel *label = [[UILabel alloc]initWithFrame:aFrame];
    label.text = @"4.您将享有招聘信息保障，如出现虚假，可申请赔偿损失(限于本地招聘)。";
    label.font = [UIFont systemFontOfSize:14];
    [containView addSubview:label];
    label.numberOfLines = 2;

    
    //立即支付Button
    UIButton *alipayButton = [[UIButton alloc]initWithFrame:CGRectMake(20, 370, SCREEN_WIDTH - 40, 44)];
    [alipayButton setBackgroundImage:[UIImage imageNamed:@"mine_btn_bg"] forState:UIControlStateNormal];
    [alipayButton setTitle:@"立即支付" forState:UIControlStateNormal];
    [self.view addSubview:alipayButton];
    //添加按钮点击方法
    [alipayButton addTarget:self action:@selector(alipayButtonClick) forControlEvents:UIControlEventTouchUpInside];
    

}

-(void)fetchVipPriceWithRequest{
    
    CGAccountDefault *account = [CGAccountDefault shareAccount];
    
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    parameters[@"account"] = account.account;
    parameters[@"password"] = account.password;
    
    ZYHRequest *request = [ZYHRequest new];
    [request postAsyncEncryptRequest:@"/main/getVIPPrice.app" parameters:parameters success:^(id responseData) {
        
        NSLog(@"认证请求成功！！");
        NSString *result = [[NSString alloc]initWithData:responseData encoding:NSUTF8StringEncoding];
        self.priceLabel.text = result;
        
    } failure:^(NSError *error) {
        
        NSLog(@"认证请求失败:%@",error);
    }];


}

#pragma mark 调用支付宝sdk
-(void)alipayButtonClick{
    //将商品信息赋予AlixPayOrder的成员变量
    Order *order = [[Order alloc] init];
    order.partner = self.partner;                 //设置商户ID
    order.seller = self.seller;                   //设置支付宝帐号
    order.tradeNO = [self generateTradeNO];       //订单ID（由商家自行制定）订单ID必须在系统中是惟一
    order.productName = @"乐目认证服务";             //商品名称
    order.productDescription = [NSString stringWithFormat:@"您将购买由乐目提供的认证会员服务 会员id:%@",[CGAccountDefault shareAccount].user_id];  //商品描述
    
    if (self.priceLabel.text.length == 0) {
        return;
    }else{
    order.amount = self.priceLabel.text;
    }

    
    order.notifyURL =  @"http://www.baidu.com";    //回调URL
    
    order.service = @"mobile.securitypay.pay";
    order.paymentType = @"1";
    order.inputCharset = @"utf-8";
    order.itBPay = @"30m";
    order.showUrl = @"m.alipay.com";
    
    //应用注册scheme,在info.plist定义URL types
    NSString *appScheme = @"schoolclient";
    
    //将商品信息拼接成字符串
    NSString *orderSpec = [order description];
    NSLog(@"orderSpec =%@",orderSpec);
    
    //签名对象 RSA 加密技术 - 加密数据 类似于MD5
    id<DataSigner> signer = CreateRSADataSigner(self.privateKey);
    NSString *signedString = [signer signString:orderSpec];
    
    //将签名成功字符串格式化为订单字符串,请严格按照该格式
    NSString *orderString = nil;
    if (signedString != nil) {
        orderString = [NSString stringWithFormat:@"%@&sign=\"%@\"&sign_type=\"%@\"",
                       orderSpec, signedString, @"RSA"];
        NSLog(@"orderString =%@",orderString);
        //支付接口
        
//        - (void)payOrder:(NSString *)orderStr
//    fromScheme:(NSString *)schemeStr
//    callback:(CompletionBlock)completionBlock
      
        [[AlipaySDK defaultService] payOrder:orderString fromScheme:appScheme callback:^(NSDictionary *resultDic) {
            
             NSLog(@"reslut = %@",resultDic);
           
            CGAlipayResult *alipay = [CGAlipayResult objectWithKeyValues:resultDic];
            
            NSLog(@"memo:%@",alipay.memo);
            NSLog(@"result:%@",alipay.result);
            NSLog(@"resultStatus:%@",alipay.resultStatus);
            int status = [alipay.resultStatus intValue];
            if (status == 9000) {
                //告诉服务器购买VIP成功
                [self returnVipSuccessToServer];
            }
    
        }];
        
    }
    
}


-(void)returnVipSuccessToServer{
    
    CGAccountDefault *account = [CGAccountDefault shareAccount];
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    parameters[@"account"] = account.account;
    parameters[@"password"] = account.password;
    ZYHRequest *request = [ZYHRequest new];
    
    [request postAsyncEncryptRequest:@"/main/updateVIP.app" parameters:parameters success:^(id responseData) {
        NSString *result = [[NSString alloc]initWithData:responseData encoding:NSUTF8StringEncoding];
        NSLog(@"result:%@",result);
        if ([result rangeOfString:@"isVip"].location != NSNotFound) {
            account.isVip = YES;
            [account saveToSandBox];
            [self.navigationController popViewControllerAnimated:YES];
        }else{
            
            [Tools alertWithTitle:@"温馨提示" andMessage:@"网络超时,请稍后再试"];
        }

    } failure:^(NSError *error) {
        [Tools alertWithTitle:@"温馨提示" andMessage:@"网络超时,请稍后再试"];
        return;
    }];
    
}

#pragma mark  产生随机订单号
- (NSString *)generateTradeNO
{
    static int kNumber = 15;
    //当前时间 + 随机数
    NSString *sourceStr = @"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    NSMutableString *resultStr = [[NSMutableString alloc] init];
    srand(time(0));
    for (int i = 0; i < kNumber; i++)
    {
        unsigned index = rand() % [sourceStr length];
        NSString *oneStr = [sourceStr substringWithRange:NSMakeRange(index, 1)];
        [resultStr appendString:oneStr];
    }
    return resultStr;
}



#pragma mark 重写表格的代理方法

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    static NSString *CellIdentifier = @"tableviewCell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:CellIdentifier];
        cell.textLabel.font = [UIFont systemFontOfSize:15];
    }
    
    if (indexPath.section == 0) {
        cell.textLabel.text = @"认证会员";
        //右侧添加一个价格标签
        self.priceLabel = [[UILabel alloc]initWithFrame:CGRectMake(SCREEN_WIDTH - 90, 0, 80, 44)];
        self.priceLabel.textAlignment = NSTextAlignmentRight;
        self.priceLabel.textColor = [UIColor orangeColor];
        [cell.contentView addSubview:self.priceLabel];
      
    }else{
        cell.imageView.image = [UIImage imageNamed:@"mine_pay_icon"];
        cell.textLabel.text = @"支付宝支付";
        UIImageView *imageView = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"mine_checked_icon"]];
        cell.accessoryView = imageView;
        
    }
    return cell;
}


//设置表头表尾高度
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    
    return 15;
}
-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    
    return 0.01;
}





@end
